#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
#define char2number(x)(x-'0'); // char to number

typedef struct ListNode{
    int value;
    struct ListNode *next;
}ListNode;

static ListNode *build_from_chars(char *chs){
    ListNode *head=0, *temp=0, *prev=0;
    int first = 1;
    int len = strlen(chs);
    char *tail = chs + len - 1 ;
    while(len-- > 0){
        temp = (ListNode *)malloc(sizeof(ListNode));
        memset(temp, 0, sizeof(temp));
        temp->value = char2number(*tail--);
        if (first) {
            head = temp;
            first = 0;
        }else{
            prev->next = temp;
        }
        prev = temp;
    }
    return head;
}

class Solution{
public:
    ListNode *l1, *l2;
    Solution(char *, char *); // char 2 number
    void show_numbers();
    int add_two_listnode();
    void free_solution();
};
Solution::Solution(char *ch1, char *ch2){
    l1 = build_from_chars(ch1);
    l2 = build_from_chars(ch2);
}
void Solution::show_numbers(){
    int number=0, factor=1;
    ListNode *ln = l1;
    while(ln!=0){
        number += ln->value * factor;
        factor *= 10;
        ln = ln->next;
    }
    printf("Number1 is: [%d]. \n", number);
    ln = l2; number=0; factor=1;
    while(ln!=0){
        number += ln->value * factor;
        factor *= 10;
        ln = ln->next;
    }
    printf("Number2 is: [%d]. \n", number);
}
int Solution::add_two_listnode(){
    int n1 = 0, n2 = 0;
    int factor = 1;
    while(l1 != 0){
        n1 += l1->value * factor;
        l1 = l1->next;
        factor *= 10;
    }
    factor = 1;
    while(l2 != 0){
        n2 += l2->value * factor;
        l2 = l2->next;
        factor *= 10;
    }
    return n1 + n2;
}
void Solution::free_solution(){
    ListNode *curr = l1, *rear = l1;
    while(curr != 0){
        rear = curr->next;
        free(curr);
        curr = rear;
    }
    curr = l2; rear = l2;
    while(curr != 0){
        rear = curr->next;
        free(curr);
        curr = rear;
    }
}


int main(int argc, char **argv){
    if (argc < 3){
        fprintf(stderr, "Usage: ./test n1, n2 \n");
        return 0;
    }
    Solution sol(argv[1], argv[2]);

    sol.show_numbers();

    int res = sol.add_two_listnode();
    printf("%d \n", res);

    sol.free_solution();
    printf("Memory is freed! \n");
    return 0;
}
